package com.zlm.tools.util;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by jinjq on 2023/5/31.
 *
 * @author jinjq
 */
public class WordBookmarkUtils {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\jinjq\\Desktop\\采购合同-技术硬件采购.docx";
        String bookmarkName = "contractNumber";
        String insertionText = "20235050617";

        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            XWPFParagraph paragraph = document.getParagraphs().stream()
                    .filter(p -> p.getCTP().getBookmarkStartList().stream()
                            .anyMatch(b -> b.getName().equals(bookmarkName)))
                    .findFirst()
                    .orElse(null);

            if (paragraph != null) {
                XWPFRun run = paragraph.createRun();
                run.setText(insertionText);
            }

            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                document.write(fos);
            }

            System.out.println("Bookmark insertion completed.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向Word文件中指定名称的书签中插入内容
     * @param filePath
     * @param docNumber
     * @param bookmarkName
     */
    public static void insertContractNumberToWord(String filePath,String docNumber,String bookmarkName){
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            XWPFParagraph paragraph = document.getParagraphs().stream()
                    .filter(p -> p.getCTP().getBookmarkStartList().stream()
                            .anyMatch(b -> b.getName().equals(bookmarkName)))
                    .findFirst()
                    .orElse(null);

            if (paragraph != null) {
                XWPFRun run = paragraph.createRun();
                run.setText(docNumber);
            }

            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                document.write(fos);
            }

            System.out.println("Bookmark insertion completed.");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
